URLString   A
last analyzed

Complexity

Total Complexity 15

Size/Duplication

Total Lines 71
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
wmc 15
eloc 37
dl 0
loc 71
c 0
b 0
f 0
ccs 29
cts 29
cp 1
rs 10

7 Functions

Rating   Name   Duplication   Size   Complexity  
A setPath 0 9 3
A create 0 8 1
A constructor 0 5 1
A toString 0 10 3
A setSearchParams 0 9 3
A setUrl 0 6 2
A urlReducer 0 7 2
1
import { URL } from 'node:url'
2
3
export default class URLString {
4
  constructor () {
5 25
    this.url = null
6 25
    this.path = {}
7 25
    this.searchParams = {}
8
  }
9
10
  setUrl (url) {
11 25
    if (!url || url.constructor !== String) {
12 1
      throw new Error('url isnt a valid string')
13
    }
14 24
    this.url = new URL(url).href
15
  }
16
17
  setSearchParams (searchParams) {
18 22
    if (!searchParams) {
19 13
      return
20
    }
21 9
    if (searchParams.constructor !== Object) {
22 1
      throw new Error('searchParams isnt a valid object')
23
    }
24 8
    this.searchParams = searchParams
25
  }
26
27
  setPath (path) {
28 23
    if (!path) {
29 1
      return
30
    }
31 22
    if (path.constructor !== Object) {
32 1
      throw new Error('path isnt a valid object')
33
    }
34 21
    this.path = path
35
  }
36
37
  urlReducer (accumulator, [key, value]) {
38 34
    if (!value) {
39 2
      return accumulator + '/' + key
40
    }
41
42 32
    return accumulator + '/' + key + '/' + value
43
  }
44
45
  toString () {
46 21
    const completeUrl = new URL(Object.entries(this.path).reduce(this.urlReducer, this.url))
47 21
    Object.entries(this.searchParams).forEach(([searchParam, searchValue]) => {
48 9
      if (searchValue) {
49 7
        completeUrl.searchParams.append(searchParam, searchValue)
50
      }
51
    })
52
53 21
    return completeUrl.href
54
  }
55
56
  /**
57
     * Generate an url from the url, path and search params
58
     *
59
     * @param {string} url
60
     * @param {object} path
61
     * @param {object} searchParams
62
     *
63
     * @return {string}
64
     */
65
  static create ({ url, path, searchParams }) {
66 25
    const newUrl = new URLString()
67 25
    newUrl.setUrl(url)
68 23
    newUrl.setPath(path)
69 22
    newUrl.setSearchParams(searchParams)
70
71 21
    return newUrl.toString()
72
  }
73
}
74